// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// j [author] rhyme_lph
// W [email]  rhymelph@gmail.com
// S [github] https://github.com/rhymelph

import 'dart:io';

import 'package:base_plugin/base_plugin.dart';
import 'package:dio/dio.dart';
import 'package:finance_app/src/entities/business_contact_entity.dart';
import 'package:finance_app/src/entities/soa_entity.dart';
import 'package:finance_app/src/http_service/http_statement_of_account_service.dart';
import 'package:finance_app/src/utils/file_utils.dart';
import 'package:flutter/material.dart';

class StatementOfAccountProvider extends BaseProvider<SOAEntity> {
  BusinessContactEntity contact;
  FocusNode instructionsFocusNode = FocusNode();
  TextEditingController instructionsController = TextEditingController();

  TextEditingController noteController = TextEditingController();
  FocusNode noteFocusNode = FocusNode();

  @override
  void dispose() {
    super.dispose();
    instructionsFocusNode.dispose();
    instructionsController.dispose();
    noteController.dispose();
    noteFocusNode.dispose();
  }

  @override
  Future get dataFuture =>
      HttpStatementOfAccountService.getPaymentInstruction(contact.id);

  @override
  FutureOr<SOAEntity> transformData(SOAEntity d, bool isCache) {
    instructionsController.text = d.paymentInstruction;
    noteController.text = d.additionalNote;
    return d;
  }

  void unFocus() {
    instructionsFocusNode.unfocus();
    noteFocusNode.unfocus();
  }

  CancelToken cancelToken = CancelToken();

  void onNext() async {
    unFocus();
    // if (instructionsController.text.length == 0) {
    //   showToast('Please enter payment instructions');
    //   return;
    // }

    File file;
    obtainContext?.call((context) async {
      BaseConfig.dialogBase
          .showLoadingDialog(context: context, text: 'loading...');
      file = await FileUtils.getSOAPdfFile(
          'soa', contact.id, instructionsController.text, noteController.text,
          cancelToken: cancelToken,
          onReceiverProgress: (int count, int total) {});
      Navigator.of(context).pop();
      if (file != null) {
        print(file.lengthSync());
        FileUtils.openFile(file);
      }
    });
  }
}
